package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//组成集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId);
		//从集合中获取对应的播放时长 userid和trackId
		Query query = Query.query(Criteria.where("trackId").is(trackId));

		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断
		if(null != userListenProcess){
			return userListenProcess.getBreakSecond();
		}

		return new BigDecimal(0.00);
	}

	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//先查询MongoDB中是否有该声音的播放记录
		//组成集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId);
		//从集合中获取对应的播放时长；userId and trackId
		Query query = Query.query(Criteria.where("userId").is(userListenProcessVo.getTrackId()));
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断
		if(null != userListenProcess){
			//覆盖声音播放
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setUpdateTime(userListenProcess.getUpdateTime());
		}else{
			//新增播放进度
			userListenProcess = new UserListenProcess();
			//赋值
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
		}
		//保存数据
		mongoTemplate.save(userListenProcess,collectionName);
		//利用分布式锁思想解决重复播放问题，避免恶意刷单
		//key=userId:trackId;value="1";24H
		String key = userId+":"+userListenProcess.getTrackId();
		Boolean result = redisTemplate.opsForValue().setIfAbsent(key,"1",24, TimeUnit.HOURS);
		//判断当前结果result
		if(result){
			//说明当前这个用户第一次播放，专辑+声音的播放量+1
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setCount(1);
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setTrackId(userListenProcess.getTrackId());
			trackStatMqVo.setAlbumId(userListenProcess.getAlbumId());
			String uuid = UUID.randomUUID().toString().replaceAll("-","");
			trackStatMqVo.setBusinessNo(uuid);
			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}
	}

	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		//创建map集合
		Map<String,Object> map = new HashMap<>();
		//数据存储在MongoDB上，获取集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId);
		//设置查询条件
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC,"updateTime")).limit(1);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//判断
		if(null != userListenProcess){
			map.put("albumId",userListenProcess.getAlbumId());
			map.put("trackId",userListenProcess.getTrackId());
		}
		//返回数据
		return map;
	}
}
